import axios from "axios";
import type { AxiosResponse, AxiosRequestConfig,AxiosError } from 'axios'
import storage from 'store'
import store from "../store/index";
import { ElMessage ,ElLoading} from 'element-plus'
// axios.create
const request = axios.create({
    baseURL: '/api',
    timeout: 60000
})
let loading:any = {}
let timer:any = ''
request.interceptors.request.use((config: AxiosRequestConfig): AxiosRequestConfig => {
    //设置请求头
    // @ts-ignore
    config.headers.token = storage.get("token");
    loading = ElLoading.service({
        lock: true,
        text: 'Loading',
        background: 'rgba(0, 0, 0, 0.7)',
    })
    return config
}, (error:AxiosError):Promise<AxiosError> => {
    return Promise.reject(error)
});
//HTTPresponse拦截
request.interceptors.response.use((res:AxiosResponse):AxiosResponse => {
    if(loading.close){
        loading.close()
    }

    if(res.status === 200 && res.data.code === 0){
        return res.data
    }else {
        ElMessage.error(res.data.msg)
        if(res.data.code === 401){
            store.dispatch("LoginOut")
        }
        return Promise.reject(res);
    }
}, (error:AxiosError):Promise<AxiosError> => {
    ElMessage.error('系统错误！')
    if(loading.close){
        loading.close()
    }
    return Promise.reject(error);
})

export default request;
